package com.wuliupai.delivery.wuliupaidelivery.activity;

import android.app.AlertDialog;
import android.content.ClipboardManager;
import android.content.Intent;
import android.text.TextPaint;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.wuliupai.delivery.wuliupaidelivery.App;
import com.wuliupai.delivery.wuliupaidelivery.R;
import com.wuliupai.delivery.wuliupaidelivery.bean.OrderBean;
import com.wuliupai.delivery.wuliupaidelivery.bean.PayBean;
import com.wuliupai.delivery.wuliupaidelivery.constants.Flag;
import com.wuliupai.delivery.wuliupaidelivery.constants.InterfaceNet;
import com.wuliupai.delivery.wuliupaidelivery.constants.Value;
import com.wuliupai.delivery.wuliupaidelivery.net.NetResultOperate;
import com.wuliupai.delivery.wuliupaidelivery.utils.CityUtil;
import com.wuliupai.delivery.wuliupaidelivery.utils.JsonUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.SelectUtil;
import com.wuliupai.delivery.wuliupaidelivery.utils.StringUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;

/**
 * Descriptions：订单详情
 * <p>
 * Author：ChenME
 * Date：11/18/2016
 * Email：ibelieve1210@163.com
 */
@EActivity(R.layout.activity_order_detail)
public class OrderDetailActivity extends AppBaseActivity {

    @ViewById(R.id.tv_orderCode)
    TextView tv_orderCode;//订单号
    @ViewById(R.id.tv_orderTime)
    TextView tv_orderTime;//时间
    @ViewById(R.id.tv_orderState)
    TextView tv_orderState;//状态

    @ViewById(R.id.tv_fromPerson)
    TextView tv_fromPerson;//发货人
    @ViewById(R.id.tv_fromPhone)
    TextView tv_fromPhone;//发货电话
    @ViewById(R.id.tv_fromAddress)
    TextView tv_fromAddress;//发货地址

    @ViewById(R.id.tv_toPerson)
    TextView tv_toPerson;//收货人
    @ViewById(R.id.tv_toPhone)
    TextView tv_toPhone;//收货电话
    @ViewById(R.id.tv_toAddress)
    TextView tv_toAddress;//收货地址

    @ViewById(R.id.tv_goodsName)
    TextView tv_goodsName;//货物名称
    @ViewById(R.id.tv_goodsInfo)
    TextView tv_goodsInfo;//货物重量、体积、件数
    @ViewById(R.id.tv_goodsRemark)
    TextView tv_goodsRemark;//备注

    @ViewById(R.id.tv_userType)
    TextView tv_userType;//用户类型

    @ViewById(R.id.tv_salesman)
    TextView tv_salesman;//业务员

    @ViewById(R.id.tv_payWay)
    TextView tv_payWay;//支付方式
    @ViewById(R.id.tv_payTotal)
    TextView tv_payTotal;//运费总价
    @ViewById(R.id.tv_alreadyPay)
    TextView tv_alreadyPay;//实际已付
    @ViewById(R.id.tv_total)
    TextView tv_total;//合计金额

    @ViewById(R.id.tv_payDetail)
    TextView tv_payDetail;//支付信息详情
    @ViewById(R.id.tv_lastPay)
    TextView tv_lastPay;//最终支付

    @ViewById(R.id.rl_allBtn)
    RelativeLayout rl_allBtn;//按钮的整体布局

    @Extra("orderId")
    String orderId;

    private String orderCnt = "";

    private int dealPrice;//应付金额（分）
    private int actualMoney;//已支付金额（分）
    private String lastMoney;//最终支付金额（元）

    private String fromPerson = "";
    private String fromPhone = "";
    private String toPerson = "";
    private String toPhone = "";
    private String orderCode = "";
    private String orderWeight = "";//重量
    private String orderVolume = "";//体积
    private String goodsName = "";//名称
    private String endWarehouse = "";//目的仓

//    private LocalBroadcastManager lbm;

    private GeoCoder mSearch;
    private LatLng latlngEndFrom;//出发地导航的结束点
    private LatLng latlngEndTo;//目的地导航的结束点

    private LatLng latlngEndFromByBaidu;//出发地导航的结束点,百度返回
    private LatLng latlngEndToByBaidu;//目的地导航的结束点,百度返回

    private boolean isCanClickBackBtn = true;

//    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            String action = intent.getAction();
//            switch (action) {
//                case Flag.BORDERCAST_CLOSE_SCAN:
//                    finish();
//                    animUtils.leftInAnimation(OrderDetailActivity.this);
//                    break;
//            }
//        }
//    };

    @AfterViews
    void onPageStart() {
        setDefaultTitle(this, R.string.string_title_order_detail);

//        registerMyReceiver();
        mSearch = GeoCoder.newInstance();

        tv_fromAddress.setOnClickListener(v -> {
            startNavigate(true);
        });
        tv_fromAddress.setOnLongClickListener(v -> {
            copyText2Clipboard(tv_fromAddress, true);
            return true;
        });

        tv_toAddress.setOnClickListener(v -> {
            startNavigate(false);
        });
        tv_toAddress.setOnLongClickListener(v -> {
            copyText2Clipboard(tv_toAddress, false);
            return true;
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getOrderDetail();//获取订单详情并显示
    }

//    /**
//     * 注册广播
//     */
//    private void registerMyReceiver() {
//        lbm = LocalBroadcastManager.getInstance(this);
//        IntentFilter filter = new IntentFilter();
//        filter.addAction(Flag.BORDERCAST_CLOSE_SCAN);
//        lbm.registerReceiver(broadcastReceiver, filter);
//    }

    /**
     * 显示导航时定位失败的提示
     */
    private void showLocationErrDialog(boolean isStart) {
        String msg = isStart ? "抱歉，未获取到发货地的经纬度！可长按地址栏进行复制。"
                : "抱歉，未获取到收货地的经纬度！可长按地址栏进行复制。";
        new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage(msg)
                .setNegativeButton("确定", (dialogInterface, i) -> {
                })
                .show();
    }

    /**
     * 显示定位地点
     *
     * @param isStart
     */
    public void startNavigate(boolean isStart) {
        LatLng pointEnd = null == latlngEndTo ? latlngEndToByBaidu : latlngEndTo;
        if (isStart) {
            pointEnd = null == latlngEndFrom ? latlngEndFromByBaidu : latlngEndFrom;
        }
        if (null == pointEnd) {
            showLocationErrDialog(isStart);
            return;
        }

        ShowLocationActivity_.intent(this).endLatLng(pointEnd).start();
        animUtils.leftInAnimation(this);
    }

    private void copyText2Clipboard(TextView textView, boolean isStart) {
        ClipboardManager mClipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        mClipboardManager.setText(textView.getText());
        String toast = isStart ? "发货地址已复制成功！" : "成功复制收货地址！";
        App.toast(toast);
    }


    /**
     * 开启反地理编码
     *
     * @param cityFrom    发货地市
     * @param addressFrom 发货地县
     * @param cityTo      收货地市
     * @param addressTo   收货地县
     * @param type        1：发货地
     *                    2：收货地
     */
    private void startGeoCode(String cityFrom, String addressFrom,
                              String cityTo, String addressTo, int type) {
        mSearch.setOnGetGeoCodeResultListener(new MyGetCeoCoderResultListener(type, cityTo, addressTo));
        mSearch.geocode(new GeoCodeOption().city(1 == type ? cityFrom : cityTo)
                .address(1 == type ? addressFrom : addressTo));
    }

    /**
     * 获取订单详情
     */
    private void getOrderDetail() {
        OrderBean orderDetailBean = new OrderBean();
        orderDetailBean.setOrderId(orderId);

        String jsonOrderDetail = JsonUtils.createJsonString(orderDetailBean);
        try {
            String aesOrderDetail = JsonUtils.aes(jsonOrderDetail);
            callNet(this, InterfaceNet.Net_GetOrderDetailByOrderID, aesOrderDetail, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {

                    if (!StringUtils.isEmpty(content)) {
                        Object obj = JsonUtils.parseJsonString(content, OrderBean.class);
                        if (null != obj) {
                            if (obj instanceof OrderBean) {

                                rl_allBtn.setVisibility(View.VISIBLE);// 显示按钮

                                OrderBean bean = (OrderBean) obj;

                                endWarehouse = bean.getEndWarehouseName();//目的仓名称，打印订单使用

                                dealPrice = Integer.valueOf(bean.getDealPrice());//运费总额
                                actualMoney = Integer.valueOf(bean.getActualMoney());//已付金额

                                orderCode = bean.getOrderCode();
                                tv_orderCode.setText(orderCode);//订单号
                                tv_orderTime.setText(bean.getRefreshTime());//下单时间

                                //支付详情展示
                                tv_payTotal.setText("￥" + (dealPrice / 100));
                                tv_alreadyPay.setText("￥" + (actualMoney / 100));
                                tv_total.setText("￥" + ((actualMoney > dealPrice ? actualMoney : dealPrice) / 100));
                                tv_payDetail.setText(String.format(getString(R.string.string_orderDetail_payDetailLabel),
                                        (dealPrice / 100) + "", (actualMoney / 100) + ""));
                                int tempLastMoney = dealPrice - actualMoney;
                                lastMoney = (tempLastMoney / 100) + "";
                                if (tempLastMoney <= 0) {
                                    lastMoney = "0";
                                }

                                //需付金额展示
                                tv_lastPay.setText(tempLastMoney > 0 ? String.format(getString(R.string.string_orderDetail_payLastLabel), lastMoney) : getString(R.string.string_orderDetail_completePay));

                                //订单状态以及付款情况
                                if ("2".equals(bean.getConfirm())) {
                                    //订单已经取消
                                    tv_orderState.setText(getString(R.string.string_orderDetail_taskAlreadyCancel));
                                    tv_orderState.setTextColor(getResources().getColor(R.color.color_textRed));
                                    TextPaint tp = tv_orderState.getPaint();
                                    tp.setFakeBoldText(true);
                                } else {
                                    //订单正常进行
                                    tv_orderState.setText(SelectUtil.initOrderState().get(bean.getStatus()));//订单状态
                                }

                                fromPerson = bean.getConsignorName();
                                fromPhone = bean.getConsignorMobile();
                                toPerson = bean.getConsigneeName();
                                toPhone = bean.getConsigneeMobile();

                                CityUtil cityUtil = new CityUtil(OrderDetailActivity.this);
                                String provinceNameS = cityUtil.findProvinceName(bean.getStartProvince());
                                String cityNameS = cityUtil.findCityName(bean.getStartCity());
                                String areaNameS = cityUtil.findAreaName(bean.getStartArea());
                                String provinceNameR = cityUtil.findProvinceName(bean.getEndProvince());
                                String cityNameR = cityUtil.findCityName(bean.getEndCity());
                                String areaNameR = cityUtil.findAreaName(bean.getEndArea());

                                StringBuilder sbAddressFrom = new StringBuilder().append(provinceNameS).append(cityNameS).append(areaNameS).append(bean.getStartAddress());
                                tv_fromAddress.setText(sbAddressFrom.toString());//寄件地址
                                tv_fromPerson.setText(fromPerson);//寄件人
                                tv_fromPhone.setText(fromPhone);//寄件联系方式

                                StringBuilder sbAddressTo = new StringBuilder().append(provinceNameR).append(cityNameR).append(areaNameR).append(bean.getEndAddress());
                                tv_toAddress.setText(sbAddressTo.toString());//收件地址
                                tv_toPerson.setText(toPerson);//收件人
                                tv_toPhone.setText(toPhone);//收件人联系方式

                                goodsName = bean.getGoodsName();
                                tv_goodsName.setText(goodsName);//货物名称
                                orderWeight = StringUtils.formatWeight(bean.getGoodsWeight());//重量
                                orderVolume = StringUtils.formatVolume(bean.getGoodsVolume());//体积

                                orderCnt = bean.getGoodsCount();

                                StringBuilder sbGoodsInfo = new StringBuilder();
                                sbGoodsInfo.append(orderWeight).append("   ").append(orderVolume).append("   ").append(orderCnt).append("件");
                                tv_goodsInfo.setText(sbGoodsInfo.toString());//件数

                                String remark = bean.getRemarks();
                                if (StringUtils.isEmpty(remark)) {
                                    tv_goodsRemark.setHint("无备注");//备注
                                } else {
                                    tv_goodsRemark.setText(bean.getRemarks());//备注
                                }
                                tv_userType.setText(SelectUtil.initUserType()
                                        .get(bean.getCalculateType()));//用戶类型

                                String salesman = bean.getSalesman();
                                if (StringUtils.isEmpty(salesman)) {
                                    tv_salesman.setText(R.string.strings_common_noFill);
                                } else {
                                    tv_salesman.setText(salesman);
                                }

                                tv_payWay.setText(
                                        SelectUtil.initPayWay().get(bean.getPayType()));//支付方式

                                startGeoCode(cityNameS, areaNameS, cityNameR, areaNameR, 1);
                                initLatlng(bean);
                            }
                        }
                    }
                }

                @Override
                public void onDataEmpty(String content) {

                }

                @Override
                public void onDataEnd(String content) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化经纬度
     *
     * @param bean
     */
    private void initLatlng(OrderBean bean) {
        try {
            double startGpsX = Double.valueOf(bean.getStartGpsX());
            double startGpsY = Double.valueOf(bean.getStartGpsY());
            if (startGpsX > Value.minLatlngValue && startGpsY > Value.minLatlngValue) {
                latlngEndFrom = new LatLng(startGpsY, startGpsX);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            double endGpsX = Double.valueOf(bean.getEndGpsX());
            double endGpsY = Double.valueOf(bean.getEndGpsY());
            if (endGpsX > Value.minLatlngValue && endGpsY > Value.minLatlngValue) {
                latlngEndTo = new LatLng(endGpsY, endGpsX);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改订单
     */
    @Click(R.id.btn_modifyOrder)
    void btn_modifyOrder() {
        PlaceOrderActivityV2_.intent(OrderDetailActivity.this).orderId(orderId)
                .fromWhichPage(Flag.ToPlaceOrder_FromOrderDetail).start();
        animUtils.leftInAnimation(OrderDetailActivity.this);

    }

    /**
     * 打印订单
     */
    @Click(R.id.btn_printLabel)
    void btn_printLabel() {
        PrintLabelActivity_.intent(OrderDetailActivity.this)
                .orderCnt(orderCnt).orderCode(orderCode)
                .fromPerson(fromPerson).fromPhone(fromPhone).fromAddress(tv_fromAddress.getText().toString())
                .toPerson(toPerson).toPhone(toPhone).toAddress(tv_toAddress.getText().toString())
                .endWarehouse(endWarehouse)
                .goodsName(goodsName).weight(orderWeight).volume(orderVolume)
                .start();
        animUtils.popInAnimation(this);
    }

    /**
     * 点击支付
     */
    @Click(R.id.btn_pay)
    void orderDetailPay() {
        if (StringUtils.isEmpty(orderCode) || null == lastMoney) {
            App.toast("未获取到订单信息，无法支付！");
            return;
        }
        PayFeeActivity_.intent(OrderDetailActivity.this)
                .payBean(new PayBean(PayFeeActivity.PayType_Freight, Long.valueOf(lastMoney) * 100))
                .orderCode(orderCode)
                .startForResult(Flag.PAY_BACK);
        animUtils.popInAnimation(OrderDetailActivity.this);
    }

    /**
     * 支付(入库)
     *
     * @param resultCode
     * @param data
     */
    @OnActivityResult(Flag.PAY_BACK)
    void onResultPay(int resultCode, Intent data) {
        if (Flag.ACTIVITY_PAY_FEE == resultCode) {
            String calculateDistance = data.getStringExtra("paySuccess");
            if (calculateDistance.equals("paySuccess")) {
                getOrderDetail();
            }
        }
    }

    /**
     * 支付(签收)
     *
     * @param resultCode
     * @param data
     */
    @OnActivityResult(Flag.PAY_BACK_SIGN_IN)
    void onResultPaySignIn(int resultCode, Intent data) {
        if (Flag.ACTIVITY_PAY_FEE == resultCode) {
            String calculateDistance = data.getStringExtra("paySuccess");
            if (calculateDistance.equals("paySuccess")) {
                getOrderDetail();
            }
        }
    }

    @Override
    protected void onDestroy() {
//        unregisterMyReceiver(lbm, broadcastReceiver);
        mSearch.destroy();
        super.onDestroy();
    }

    /**
     * 反地理编码结果监听
     */
    private class MyGetCeoCoderResultListener implements OnGetGeoCoderResultListener {
        private int type;
        private String cityTo;
        private String areaTo;

        MyGetCeoCoderResultListener(int type, String cityTo, String areaTo) {
            this.type = type;
            this.cityTo = cityTo;
            this.areaTo = areaTo;
        }

        @Override
        public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
            if (geoCodeResult == null || geoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
                // 没有检索到结果
                if (1 == type) {
                    startGeoCode("", "", cityTo, areaTo, 2);
                }
                return;
            }
            try {
                double longitude = geoCodeResult.getLocation().longitude;
                double latitude = geoCodeResult.getLocation().latitude;
                // 获取地理编码结果
                if (1 == type) {
                    latlngEndFromByBaidu = new LatLng(latitude, longitude);
                    startGeoCode("", "", cityTo, areaTo, 2);
                } else {
                    latlngEndToByBaidu = new LatLng(latitude, longitude);
                }
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
//            if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
//                // 没有找到检索结果
//            }
//            // 获取反向地理编码结果
        }
    }

    @Override
    public void onBackPressed() {
        if (isCanClickBackBtn) {
            super.onBackPressed();
        }
    }
}